package com.mobile.check.present;

import android.os.Environment;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import com.mobile.check.activitys.TaskServerListActivity;
import com.mobile.check.beans.TaskInfo;
import com.mobile.check.app.R;
import com.mobile.check.db.EntityManager;
import com.mobile.check.net.Api;
import com.mobile.check.net.BaseObjBean;
import com.mobile.check.util.DownloadManager;

/**
 * 类名: TaskListPresent
 * 作者: 李学伟
 * 日期: 2020年10月08日 20:57
 * 描述:
 */
public class TaskServerListPresent extends BasePresent<TaskServerListActivity> {
    public void getTaskList(final int taskType) {
        getV().showLoadDialog();
        Observable<BaseObjBean<ArrayList<TaskInfo>>> requestObservable;
        if (taskType == 0) {
            requestObservable = Api.getApiService().taskList(getToken());
        } else {
            requestObservable = Api.getApiService().recheck_list(getToken());
        }

        requestObservable
                .compose(XApi.<BaseObjBean<ArrayList<TaskInfo>>>getApiTransformer())
                .compose(XApi.<BaseObjBean<ArrayList<TaskInfo>>>getScheduler())
                .compose(getV().<BaseObjBean<ArrayList<TaskInfo>>>bindToLifecycle())
                .map(new Function<BaseObjBean<ArrayList<TaskInfo>>, BaseObjBean<ArrayList<TaskInfo>>>() {
                    @Override
                    public BaseObjBean<ArrayList<TaskInfo>> apply(BaseObjBean<ArrayList<TaskInfo>> bean) {
                        check(bean.getData(), taskType);
                        return bean;
                    }
                })
                .subscribe(new Consumer<BaseObjBean<ArrayList<TaskInfo>>>() {
                    @Override
                    public void accept(BaseObjBean<ArrayList<TaskInfo>> objBean) {
                        getV().onSuccess(objBean.getData());
                        getV().disLoadDialog();
                    }
                }, failNeedLoginConsumer);
    }


    private void check(List<TaskInfo> list, int taskType) {
        for (TaskInfo taskInfo : list) {
            taskInfo.setTaskType(taskType);
            boolean hadDowned = null != EntityManager.getInstance().queryTaskInfoCount(taskInfo.getTask_name(), taskType, false);
            taskInfo.setHadDowned(hadDowned);
        }
        Collections.sort(list, new Comparator<TaskInfo>() {
            public int compare(TaskInfo a, TaskInfo b) {
                if (a.isHadDowned() && !b.isHadDowned()) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }


    public void startDown(List<TaskInfo> list) {
        getV().showLoadDialog();
        Observable.fromIterable(list).filter(new Predicate<TaskInfo>() {
            @Override
            public boolean test(TaskInfo taskInfo) throws Exception {
                return !taskInfo.isHadDowned();
            }
        }).flatMap(new Function<TaskInfo, ObservableSource<TaskInfo>>() {
            @Override
            public ObservableSource<TaskInfo> apply(TaskInfo info) throws Exception {
                String exportPath;
                exportPath = Environment.getExternalStorageDirectory() + "/" + getV().getString(R.string.app_name) + "/网络任务";
                String picDir = Environment.getExternalStorageDirectory() + "/" + getV().getString(R.string.app_name) + "/网络任务/图片";
                File file = new File(picDir);
                file.mkdirs();
                if (!info.isRepeatTask()) {
                    exportPath = exportPath + "/" + "检测任务";
                } else {
                    exportPath = exportPath + "/" + "复检任务";
                }
                Observable observable = DownloadManager.getInstance().download(info, exportPath, picDir);
                return observable;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<TaskInfo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TaskInfo o) {
                getV().disLoadDialog();
                if (o.getHadDowned()) {
                    EntityManager.getInstance().saveTaskInfo(o);
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                getV().disLoadDialog();
            }

            @Override
            public void onComplete() {
                getV().disLoadDialog();
                getV().downSuccess();
            }
        });
    }

}
